/*
 * Inv 2002 Semi2 Prob 2
 */


import java.util.*;
import java.util.regex.*;
import java.text.*;
import java.math.*;


public class Escape
{
    public int lowest(String[] harmful, String[] deadly)
    {
	int[][] map = new int[501][501];
	int[][] v = new int[501][501];
	for (String s:harmful) {
	    String[] s4 = s.split (" ");
	    int[] d = new int[4];
	    for (int i = 0; i < 4; ++i)
		d[i] = Integer.parseInt (s4[i]);
	    for (int x = Math.min (d[0], d[2]); x <= Math.max (d[0], d[2]); ++x)
		for (int y = Math.min (d[1], d[3]); y <= Math.max (d[1], d[3]); ++y)
		    map[x][y] = 1;
	}
	
	for (String s:deadly) {
	    String[] s4 = s.split (" ");
	    int[] d = new int[4];
	    for (int i = 0; i < 4; ++i)
		d[i] = Integer.parseInt (s4[i]);
	    for (int x = Math.min (d[0], d[2]); x <= Math.max (d[0], d[2]); ++x)
		for (int y = Math.min (d[1], d[3]); y <= Math.max (d[1], d[3]); ++y)
		    map[x][y] = 2;
	}
	LinkedList<Integer> queueX = new LinkedList<Integer> ();
	LinkedList<Integer> queueY = new LinkedList<Integer> ();
	if (map[500][500] == 2)
	    return -1;
	for (int i = 0; i < 501; ++i)
	    Arrays.fill (v[i], Integer.MAX_VALUE);
	v[0][0] = 0;
	queueX.addLast (0);
	queueY.addLast (0);
	while (!queueX.isEmpty ()) {
	    int x = queueX.removeFirst ();
	    int y = queueY.removeFirst ();
	    
	    if (x > 0) {
		if (map[x-1][y] != 2 && v[x][y] + map[x-1][y] < v[x-1][y]) {
		    queueX.addLast (x-1);
		    queueY.addLast (y);
		    v[x-1][y] = v[x][y] + map[x-1][y];
		}
	    }
	    
	    if (x < 500) {
		if (map[x+1][y] != 2 && v[x][y] + map[x+1][y] < v[x+1][y]) {
		    queueX.addLast (x+1);
		    queueY.addLast (y);
		    v[x+1][y] = v[x][y] + map[x+1][y];
		}
	    }
	    
	    if (y > 0) {
		if (map[x][y-1] != 2 && v[x][y] + map[x][y-1] < v[x][y-1]) {
		    queueX.addLast (x);
		    queueY.addLast (y-1);
		    v[x][y-1] = v[x][y] + map[x][y-1];
		}
	    }
	    if (y < 500) {
		if (map[x][y+1] != 2 && v[x][y] + map[x][y+1] < v[x][y+1]) {
		    queueX.addLast (x);
		    queueY.addLast (y+1);
		    v[x][y+1] = v[x][y] + map[x][y+1];
		}
	    }
	}
	if (v[500][500] == Integer.MAX_VALUE)
	    return -1;
	return v[500][500];
    }
    
    <%:testing-code%>
}
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!